package com.liao.rent.controller;

import com.liao.rent.config.MinioConfiguration;
import com.liao.rent.entity.JsonResult;
import com.liao.rent.utils.MinioUtils;
import com.liao.rent.utils.ResultTool;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

@Slf4j
@Tag(name = "文件上传管理")
@RestController
@RequestMapping("/oss")
public class OSSController {

    @Autowired
    private MinioUtils minioUtils;

    @Autowired
    private MinioConfiguration minioConfig;

    /**
     * 文件上传
     *
     * @param file
     */
    @Operation(summary = "文件上传")
    @PostMapping("/upload")
    public JsonResult<String> upload(@RequestParam("file") MultipartFile file) {
        try {
            //文件名
            String fileName = file.getOriginalFilename();
            String newFileName =System.currentTimeMillis() + "." + StringUtils.substringAfterLast(fileName, ".");
            //类型
            String contentType = file.getContentType();
            String url = minioUtils.uploadFile(minioConfig.getBucketName(), file, newFileName, contentType);

            return ResultTool.success(url);
        } catch (Exception e) {
            return ResultTool.fail("上传失败");
        }
    }

    /**
     * 文件批量上传
     *
     * @param files 文件数组
     */
    @Operation(summary = "文件批量上传")
    @PostMapping("/batchUpload")
    public JsonResult batchUpload(@RequestParam(value = "file",required = false) MultipartFile[] files, HttpServletRequest request) {
        /**
         * 解决前端使用FormData上传文件时，无法获取文件的问题
         * 因前端返回的表单数据是files[1],files[2],files[3]...格式所以从request中获取上传文件加入到files中
         */
            //转化成文件上传请求
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();

        if (!fileMap.isEmpty()){
            Collection<MultipartFile> multipartFiles = fileMap.values();
            files = multipartFiles.toArray(new MultipartFile[multipartFiles.size()]);
        }

        //判断是否为空
        if (files == null || files.length == 0 ) {
            return ResultTool.fail("上传失败");
        }

//创建图片地址
        ArrayList<String> urls = new ArrayList<>();

        try {
//            遍历上传图片
            for (MultipartFile file : files){
                //文件名
                String fileName = file.getOriginalFilename();
                String newFileName =System.currentTimeMillis() + "." + StringUtils.substringAfterLast(fileName, ".");
                //类型
                String contentType = file.getContentType();
                String url = minioUtils.uploadFile(minioConfig.getBucketName(), file, newFileName, contentType);
//                成功后添加图片地址
                urls.add(url);
            }

            return ResultTool.success(urls.toArray(new String[files.length]));
        } catch (Exception e) {
            return ResultTool.fail("上传失败");
        }
    }

    /**
     * 删除
     *
     * @param fileName
     */
    @Operation(summary = "删除文件")
    @DeleteMapping("/")
    public void delete(@RequestParam("fileName") String fileName) {
        minioUtils.removeFile(minioConfig.getBucketName(), fileName);
    }

    /**
     * 获取文件信息
     *
     * @param fileName
     * @return
     */
    @Operation(summary = "获取文件信息")
    @GetMapping("/info")
    public String getFileStatusInfo(@RequestParam("fileName") String fileName) {
        return minioUtils.getFileStatusInfo(minioConfig.getBucketName(), fileName);
    }

    /**
     * 获取文件外链
     *
     * @param fileName
     * @return
     */
    @Operation(summary = "获取文件外链")
    @GetMapping("/url")
    public String getPresignedObjectUrl(@RequestParam("fileName") String fileName) {
        return minioUtils.getPresignedObjectUrl(minioConfig.getBucketName(), fileName);
    }

    /**
     * 文件下载
     *
     * @param fileName
     * @param response
     */
    @Operation(summary = "文件下载")
    @GetMapping("/download")
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        try {
            InputStream fileInputStream = minioUtils.getObject(minioConfig.getBucketName(), fileName);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setContentType("application/force-download");
            response.setCharacterEncoding("UTF-8");
            IOUtils.copy(fileInputStream, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载失败");
        }
    }

}